<template>
  <div class="food-cart-container">
    <!-- 顶部标题 -->
    <div class="cart-header">
      <h1><i class="el-icon-shopping-cart-full"></i> 我的购物车</h1>
      <p>当前共有 {{ cartItems.length }} 件商品</p>
    </div>

    <!-- 购物车内容区 -->
    <div class="cart-content" v-loading="loading">
      <!-- 空购物车提示 -->
      <div v-if="cartItems.length === 0" class="empty-cart">
        <el-empty description="您的购物车还是空的，快去添加美食吧！">
          <el-button type="primary" @click="goToDishes">去添加菜品</el-button>
        </el-empty>
      </div>

      <!-- 购物车列表 -->
      <el-table 
        v-else
        :data="cartItems"
        style="width: 100%"
        class="cart-table"
      >
        <el-table-column label="菜品信息" width="350">
          <template #default="{row}">
            <div class="dish-info">
              <el-image 
                :src="row.imageUrl" 
                fit="cover" 
                class="dish-image"
              >
                <template #error>
                  <div class="image-error">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </template>
              </el-image>
              <div class="dish-details">
                <h4>{{ row.name }}</h4>
                <p class="description">{{ row.description || '暂无描述' }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="单价" width="120" align="center">
          <template #default="{row}">
            <span class="price">¥{{ row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数量" width="150" align="center">
          <template #default="{row}">
            <div class="quantity-control">
              <el-button 
                icon="el-icon-minus" 
                circle 
                size="mini"
                :disabled="row.quantity <= 1"
                @click="updateQuantity(row, row.quantity - 1)"
              ></el-button>
              <span class="quantity">{{ row.quantity }}</span>
              <el-button 
                icon="el-icon-plus" 
                circle 
                size="mini"
                @click="updateQuantity(row, row.quantity + 1)"
              ></el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="小计" width="120" align="center">
          <template #default="{row}">
            <span class="subtotal">¥{{ (row.price * row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="100">
          <template #default="{row}">
            <el-button 
              type="danger" 
              icon="el-icon-delete" 
              circle
              size="mini"
              @click="deleteItem(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 购物车底部功能区 -->
      <div class="cart-footer" v-if="cartItems.length > 0">
        <div class="total-price">
          <span>合计：</span>
          <span class="total-amount">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <div class="action-buttons">
          <el-button @click="clearCart">清空购物车</el-button>
          <el-button @click="goToDishes">继续添加菜品</el-button>
          <el-button type="primary" @click="openOrderDialog">下单</el-button>
        </div>
      </div>
    </div>

    <!-- 下单对话框 -->
    <el-dialog 
      title="确认订单信息"
      :visible.sync="orderDialogVisible"
      width="500px"
    >
      <el-form :model="orderForm" label-width="100px">
        <!-- 新增座位订单选择 -->
          <el-form-item label="关联座位订单" required>
            <el-select 
              v-model="orderForm.seatOrderId" 
              placeholder="请选择已支付的座位订单"
              clearable
              :disabled="paidSeatOrders.length === 0"
            >
              <el-option 
                v-for="order in paidSeatOrders"
                :key="order.id"
                :label="`订单ID: ${order.id}, 座位号: ${formatSeatId(order.seatId)}`"
                :value="order.id"
              ></el-option>
            </el-select>
            <p v-if="paidSeatOrders.length === 0" style="color: #F56C6C; margin-top: 5px;">
              您还没有已支付的座位订单，请先去预订座位并支付！
            </p>
          </el-form-item>
        <el-form-item label="订单总价">
          <span class="order-total-price">¥{{ totalPrice.toFixed(2) }}</span>
        </el-form-item>
        <el-form-item label="支付方式" required>
          <el-select v-model="orderForm.paymentMethod" placeholder="请选择支付方式">
            <el-option label="支付宝" value="alipay"></el-option>
            <el-option label="微信支付" value="wechat"></el-option>
            <el-option label="银行卡" value="bankcard"></el-option>
            <el-option label="现金" value="cash"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息">
          <el-input 
            type="textarea" 
            v-model="orderForm.remark" 
            placeholder="请输入备注信息（如特殊要求等）"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="orderDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOrder" :loading="submitting">确认下单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getUserId, getToken } from '@/utils/auth.js';
import { 
  getDishcartByUserId, 
  updateDishcart, 
  delDishcart, 
  clearDishcartByUserId 
} from '@/api/Dishcart.js';
import { getDish } from '@/api/Dish.js';
import { addDishorder } from '@/api/Dishorder.js';
import { getSeatorderByUserId } from '@/api/Seatorder.js'; // 导入座位订单接口
import MapUtils from '@/utils/mapUtils';

export default {
  name: 'FoodCart',
  data() {
    return {
      cartItems: [],      // 购物车商品列表
      loading: true,      // 加载状态
      orderDialogVisible: false, // 下单对话框显示状态
      submitting: false,  // 提交订单状态
      paidSeatOrders: [], // 已支付的座位订单
      orderForm: {
        seatOrderId: null, // 关联的座位订单ID
        paymentMethod: '', // 支付方式
        remark: ''         // 备注
      }
    };
  },
  computed: {
    // 计算购物车总价
    totalPrice() {
      return this.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity);
      }, 0);
    },
    
  },
  created() {
    // 检查登录状态
    this.checkLoginStatus();
    //加载映射关系room,seat,dish,id->名映射
     this.loadMaputils()
    // 加载购物车数据
    this.loadCartData().then(() => {
    this.updateCartCount(); // 加载完成后更新
  });
  },
  methods: {
    async loadMaputils() {
      try {
        const result=MapUtils.isEmpty()
          if(result.isSeatEmpty){
            await listSeat();
          }
      } catch (error) {
        console.error('座位加载映射失败:', error);
      }
    },
    formatSeatId(id) {
      return MapUtils.getSeatNumber(id);
    },
    updateCartCount() {
       this.$store.dispatch('cart/updateCartCount', this.cartItems.length);
    },
    // 检查登录状态
    checkLoginStatus() {
      if (!getToken()) {
        this.$message.warning('您还未登录，请先登录');
        this.$router.push('/login');
      }
    },
    
    // 加载购物车数据
    async loadCartData() {
      try {
        this.loading = true;
        const userId = getUserId();
        
        // 1. 获取用户购物车数据
        const cartRes = await getDishcartByUserId(userId);
        if (!cartRes || cartRes.code !== 200 || !cartRes.rows || cartRes.rows.length === 0) {
          this.cartItems = [];
          this.loading = false;
          return;
        }
        
        // 2. 获取每个菜品的详细信息
        const dishPromises = cartRes.rows.map(async cartItem => {
          const dishRes = await getDish(cartItem.dishId);
          if (dishRes && dishRes.code === 200 && dishRes.data) {
            return {
              ...cartItem,
              ...dishRes.data,
              // 添加购物车项ID
              cartId: cartItem.id
            };
          }
          return null;
        });
        
        // 3. 等待所有菜品信息加载完成
        const items = await Promise.all(dishPromises);
        this.cartItems = items.filter(item => item !== null);
        
      } catch (error) {
        console.error('加载购物车数据失败:', error);
        this.$message.error('加载购物车数据失败，请稍后重试');
      } finally {
        this.loading = false;
        this.updateCartCount();
      }
    },
    
    // 更新商品数量
    async updateQuantity(item, newQuantity) {
      try {
        // 确保最小数量为1
        if (newQuantity < 1) newQuantity = 1;
        
        // 更新本地数据
        const originalQuantity = item.quantity;
        item.quantity = newQuantity;
        
        // 发送更新请求到后端
        await updateDishcart({
          id: item.cartId,
          quantity: newQuantity
        });
        
        this.$message.success('数量更新成功');
        this.updateCartCount();
      } catch (error) {
        console.error('更新数量失败:', error);
        // 恢复原始数量
        item.quantity = originalQuantity;
        this.$message.error('更新数量失败，请稍后重试');
      }
    },
    
    // 删除购物车项
    async deleteItem(item) {
      try {
        this.$confirm('确定要从购物车中删除该菜品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 发送删除请求
          await delDishcart(item.cartId);
          
          // 更新本地数据
          this.cartItems = this.cartItems.filter(i => i.cartId !== item.cartId);
          
          this.$message.success('删除成功');
          this.updateCartCount();
        });
      } catch (error) {
        console.error('删除失败:', error);
        this.$message.error('删除失败，请稍后重试');
      }
    },
    
    // 清空购物车
    clearCart() {
      this.$confirm('确定要清空整个购物车吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const userId = getUserId();
          // 发送清空购物车请求
          await clearDishcartByUserId(userId);
          
          // 更新本地数据
          this.cartItems = [];
          
          this.$message.success('购物车已清空');
          this.updateCartCount();
        } catch (error) {
          console.error('清空购物车失败:', error);
          this.$message.error('清空购物车失败，请稍后重试');
        }
      });
    },
    
    // 跳转到菜品页面
    goToDishes() {
      this.$router.push('/dishes');
    },
    
    
     // 打开下单对话框
    async openOrderDialog() {
      if (this.cartItems.length === 0) {
        this.$message.warning('购物车为空，请先添加菜品');
        return;
      }
      
      try {
        // 获取已支付的座位订单
        const userId = getUserId();
        const res = await getSeatorderByUserId(userId);
        
        if (res && res.code === 200 && res.rows) {
          // 筛选状态为2（已支付）的座位订单
          this.paidSeatOrders = res.rows.filter(order => order.status === 2);
        } else {
          this.paidSeatOrders = [];
        }
      } catch (error) {
        console.error('获取座位订单失败:', error);
        this.$message.error('获取座位订单失败，请稍后重试');
        this.paidSeatOrders = [];
      }
      
      // 重置表单
      this.orderForm = {
        seatOrderId: null,
        paymentMethod: '',
        remark: ''
      };
      this.orderDialogVisible = true;
    },
    
    // 提交订单
    async submitOrder() {
      if (!this.orderForm.paymentMethod) {
        this.$message.warning('请选择支付方式');
        return;
      }
      // 检查座位订单是否已选择
      if (!this.orderForm.seatOrderId) {
        this.$message.warning('请选择已支付的座位订单');
        return;
      }
      
      try {
        this.submitting = true;
        
        // 准备订单数据
        const orderData = {
          userId: getUserId(),
            seatOrderId: this.orderForm.seatOrderId, // 关联的座位订单ID
          totalPrice: this.totalPrice,
          paymentMethod: this.orderForm.paymentMethod,
          remark: this.orderForm.remark,
          dishorderitemList: this.cartItems.map((item, index) => ({
            dishId: item.id,
            quantity: item.quantity,
            price: item.price,
            subtotal: item.price * item.quantity,
            index: index + 1
          }))
        };
        
        // 发送下单请求
        const res = await addDishorder(orderData);
        if (res && res.code === 200) {
          this.$message.success('下单成功！');
          
          // 清空购物车
          await clearDishcartByUserId(getUserId());
          this.cartItems = [];
          
          // 关闭对话框
          this.orderDialogVisible = false;
          this.updateCartCount();
        } else {
          this.$message.error('下单失败，请稍后重试');
        }
      } catch (error) {
        console.error('下单失败:', error);
        this.$message.error('下单失败，请稍后重试');
      } finally {
        this.submitting = false;
      }
    }
  }
};
</script>

<style scoped>
.food-cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.cart-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.cart-header h1 {
  color: #333;
  font-size: 28px;
  margin-bottom: 10px;
}

.cart-header p {
  color: #666;
  font-size: 16px;
}

.cart-content {
  min-height: 400px;
}

.empty-cart {
  text-align: center;
  padding: 50px 0;
}

.dish-info {
  display: flex;
  align-items: center;
}

.dish-image {
  width: 80px;
  height: 80px;
  border-radius: 5px;
  margin-right: 15px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-error {
  color: #c0c4cc;
  font-size: 24px;
}

.dish-details h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.description {
  color: #999;
  font-size: 13px;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}

.price, .subtotal {
  font-weight: bold;
  color: #e6a23c;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity {
  margin: 0 10px;
  min-width: 30px;
  text-align: center;
  font-weight: bold;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.total-price {
  font-size: 18px;
}

.total-amount {
  font-size: 24px;
  color: #e6a23c;
  font-weight: bold;
  margin-left: 5px;
}

.action-buttons button {
  margin-left: 10px;
}

.order-total-price {
  font-size: 24px;
  color: #e6a23c;
  font-weight: bold;
}

.cart-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.cart-table ::v-deep .el-table__row {
  transition: all 0.3s;
}

.cart-table ::v-deep .el-table__row:hover {
  background-color: #f8f9fa;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>